package com.ruoyi.resume.utils;

import com.ruoyi.resume.domain.model.resumeProfile.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.YearMonth;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ResumeParserUtil {

    private static final Logger logger = LoggerFactory.getLogger(ResumeParserUtil.class);

    /**
     * 将 GLM 模型返回的整体简历文本分割为各个部分
     */
    public static Map<String, String> splitIntoSections(String resumeParts) {
        Map<String, String> sectionMap = new HashMap<>();
        String[] resumeData = resumeParts.split("\n");
        String currentSection = "";
        StringBuilder currentContent = new StringBuilder();

        // 正则匹配简历各部分标题
        Pattern sectionPattern = Pattern.compile("^ *(基本信息|教育经历|实习经历|工作经历|项目经历|相关技能|其他信息)[:：]? *$");
        for (String part : resumeData) {
            part = part.trim().replace("#", "");
            // 跳过特定标签
            if (part.equals("<think>") || part.equals("</think>")) continue;
            if (part.startsWith("(") && part.endsWith(")")) continue;

            Matcher matcher = sectionPattern.matcher(part);
            if (matcher.find()) {
                if (!currentSection.isEmpty()) {
                    sectionMap.put(currentSection, ResumeProcessingUtils.cleanMarkdown(currentContent.toString()));
                }
                currentSection = matcher.group(1);
                currentContent.setLength(0);
            } else if (!part.isEmpty()){
                currentContent.append(part).append('\n');
            }
        }
        if (!currentSection.isEmpty()){
            sectionMap.put(currentSection, ResumeProcessingUtils.cleanMarkdown(currentContent.toString()));
        }
        return sectionMap;
    }

    /**
     * 根据 GLM 模型返回的文本解析出 BasicInfo 对象
     */
    public static BasicInfo parseBasicInfo(String modelOutput) {
        BasicInfo basicInfo = new BasicInfo();
        basicInfo.setName(extractValue(modelOutput, "姓名"));
        basicInfo.setPhone(extractValue(modelOutput, "电话"));
        basicInfo.setSchool(extractValue(modelOutput, "学校"));
        basicInfo.setNation(extractValue(modelOutput, "民族"));
        basicInfo.setDegree(extractValue(modelOutput, "学历"));
        basicInfo.setEmail(extractValue(modelOutput, "电子邮件"));
        basicInfo.setResidence(extractValue(modelOutput, "居住地"));
        basicInfo.setPoliticalStatus(extractValue(modelOutput, "政治面貌"));
        basicInfo.setGender(extractValue(modelOutput, "性别"));
        basicInfo.setAge(extractAgeValue(modelOutput));
        return basicInfo;
    }

    /**
     * 通用文本抽取工具方法，根据字段名提取对应值
     */
    public static String extractValue(String text, String field) {
        String pattern = field + ":\\s*(.*)";
        Pattern regex = Pattern.compile(pattern);
        Matcher matcher = regex.matcher(text);
        if (matcher.find()){
            String value = matcher.group(1).trim();
            return "无".equals(value) ? "" : value;
        }
        return "";
    }

    /**
     * 提取年龄字段中的数字
     */
    public static Integer extractAgeValue(String text) {
        String pattern = "年龄:\\s*(\\d+)";
        Pattern regex = Pattern.compile(pattern);
        Matcher matcher = regex.matcher(text);
        if (matcher.find()){
            try {
                return Integer.parseInt(matcher.group(1).trim());
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 解析 GLM 返回的文本生成教育背景列表
     */
    public static List<EducationBackground> parseEducationBackground(String text) {
        List<EducationBackground> educationBackgrounds = new ArrayList<>();
        String[] entries = text.split("\n\n");
        for (String entry : entries) {
            EducationBackground education = new EducationBackground();
            education.setSchoolName(extractValue(entry, "学校名称"));
            education.setMajorName(extractValue(entry, "专业名称"));

            String startTimeStr = extractValue(entry, "起始时间");
            if (!startTimeStr.isEmpty()){
                try {
                    education.setStartTime(YearMonth.parse(startTimeStr));
                } catch (DateTimeParseException e) {
                    logger.warn("起始时间格式不正确: {}", startTimeStr);
                    education.setStartTime(null);
                }
            }

            String endTimeStr = extractValue(entry, "终止时间");
            if (!endTimeStr.isEmpty()){
                if ("至今".equals(endTimeStr)){
                    education.setEndTime(YearMonth.of(9999, 1));
                } else {
                    try {
                        education.setEndTime(YearMonth.parse(endTimeStr));
                    } catch (DateTimeParseException e) {
                        logger.warn("终止时间格式不正确: {}", endTimeStr);
                        education.setEndTime(null);
                    }
                }
            }

            education.setDegree(extractValue(entry, "学历"));
            String courses = extractValue(entry, "相关课程列表");
            if (!"无".equals(courses) && !courses.isEmpty()){
                education.setRelatedCourses(courses);
            } else {
                education.setRelatedCourses(null);
            }
            educationBackgrounds.add(education);
        }
        return educationBackgrounds;
    }

    /**
     * 解析 GLM 返回的文本生成工作经历列表
     */
    public static List<WorkExperience> parseWorkExperience(String text) {
        List<WorkExperience> workExperiences = new ArrayList<>();
        String[] entries = text.split("\n\n");
        for (String entry : entries) {
            WorkExperience work = new WorkExperience();
            work.setCompanyName(extractValue(entry, "公司名称"));
            work.setJobTitle(extractValue(entry, "职位"));
            work.setDepartment(extractValue(entry, "部门"));

            String startTimeStr = extractValue(entry, "起始时间");
            if (!startTimeStr.isEmpty()){
                try {
                    work.setStartTime(YearMonth.parse(startTimeStr));
                } catch (DateTimeParseException e) {
                    logger.warn("起始时间格式不正确: {}", startTimeStr);
                    work.setStartTime(null);
                }
            }

            String endTimeStr = extractValue(entry, "终止时间");
            if (!endTimeStr.isEmpty()){
                if ("至今".equals(endTimeStr)){
                    work.setEndTime(YearMonth.of(9999, 1));
                } else {
                    try {
                        work.setEndTime(YearMonth.parse(endTimeStr));
                    } catch (DateTimeParseException e) {
                        logger.warn("终止时间格式不正确: {}", endTimeStr);
                        work.setEndTime(null);
                    }
                }
            }

            work.setProjectName(extractValue(entry, "项目名称"));
            work.setProjectDescription(extractValue(entry, "项目描述"));
            workExperiences.add(work);
        }
        return workExperiences;
    }

    /**
     * 解析 GLM 返回的文本生成实习经历列表
     */
    public static List<InternshipExperience> parseInternshipExperience(String text) {
        List<InternshipExperience> internshipExperiences = new ArrayList<>();
        String[] entries = text.split("\n\n");
        for (String entry : entries) {
            InternshipExperience internship = new InternshipExperience();
            internship.setCompanyName(extractValue(entry, "公司名称"));
            internship.setJobTitle(extractValue(entry, "职位"));
            internship.setDepartment(extractValue(entry, "部门"));

            String startTimeStr = extractValue(entry, "起始时间");
            if (!startTimeStr.isEmpty()){
                try {
                    internship.setStartTime(YearMonth.parse(startTimeStr));
                } catch (DateTimeParseException e) {
                    logger.warn("起始时间格式不正确: {}", startTimeStr);
                    internship.setStartTime(null);
                }
            }

            String endTimeStr = extractValue(entry, "终止时间");
            if (!endTimeStr.isEmpty()){
                if ("至今".equals(endTimeStr)){
                    internship.setEndTime(YearMonth.of(9999, 1));
                } else {
                    try {
                        internship.setEndTime(YearMonth.parse(endTimeStr));
                    } catch (DateTimeParseException e) {
                        logger.warn("终止时间格式不正确: {}", endTimeStr);
                        internship.setEndTime(null);
                    }
                }
            }

            internship.setProjectName(extractValue(entry, "项目名称"));
            internship.setProjectDescription(extractValue(entry, "项目描述"));
            internshipExperiences.add(internship);
        }
        return internshipExperiences;
    }

    /**
     * 解析 GLM 返回的文本生成项目经历列表
     */
    public static List<ProjectExperience> parseProjectExperience(String text) {
        List<ProjectExperience> projectExperiences = new ArrayList<>();
        String[] entries = text.split("\n\n");

        for (String entry : entries) {
            ProjectExperience project = new ProjectExperience();
            project.setProjectName(extractValue(entry, "项目名称"));
            project.setDescription(extractValue(entry, "项目描述"));
            project.setRole(extractValue(entry, "角色"));

            String startTimeStr = extractValue(entry, "起始时间");
            if (!startTimeStr.isEmpty()) {
                try {
                    project.setStartDate(YearMonth.parse(startTimeStr).toString()); // 格式化为标准字符串
                } catch (DateTimeParseException e) {
                    logger.warn("开始时间格式不正确: {}", startTimeStr);
                    project.setStartDate(null);
                }
            }

            String endTimeStr = extractValue(entry, "终止时间");
            if (!endTimeStr.isEmpty()) {
                if ("至今".equals(endTimeStr)) {
                    project.setEndDate("9999-01"); // 代表至今
                } else {
                    try {
                        project.setEndDate(YearMonth.parse(endTimeStr).toString());
                    } catch (DateTimeParseException e) {
                        logger.warn("结束时间格式不正确: {}", endTimeStr);
                        project.setEndDate(null);
                    }
                }
            }

            projectExperiences.add(project);
        }
        return projectExperiences;
    }

    /**
     * 解析 GLM 返回的文本生成相关技能列表
     */
    public static List<RelatedSkill> parseRelatedSkills(String text) {
        List<RelatedSkill> relatedSkills = new ArrayList<>();
        String[] entries = text.split("\n\n");

        for (String entry : entries) {
            if (!entry.trim().isEmpty()) {
                RelatedSkill skill = new RelatedSkill();
                skill.setSkill(extractValue(entry, "技能名称"));
                skill.setSkillDescription(extractValue(entry, "技能描述"));
                relatedSkills.add(skill);
            }
        }
        return relatedSkills;
    }


}
